package com.xms.utils;

import java.lang.reflect.Field;

/**
 * <p>
 * RefletUtil
 * </p>
 *
 * @author migo
 * @since 2021/11/4
 */
public class RefletUtil {
    /**
     * 设置对象属性值
     * @param entity
     * @param field
     * @param value
     * @throws IllegalAccessException
     */
    public static void setFieldValue(Object entity, Field field, Object value) throws IllegalAccessException {
        if (value == null) {
            return;
        }
        field.setAccessible(true);
        switch (field.getType().getSimpleName()) {
            case "Integer":
                field.set(entity, Integer.valueOf(value.toString()));
                break;
            case "int":
                field.setInt(entity, Integer.parseInt(value.toString()));
                break;
            case "Long":
                field.set(entity, Long.valueOf(value.toString()));
                break;
            case "long":
                field.setLong(entity, Long.parseLong(value.toString()));
                break;
            case "Short":
                field.set(entity, Short.valueOf(value.toString()));
                break;
            case "short":
                field.setShort(entity, Short.parseShort(value.toString()));
                break;
            case "Float":
                field.set(entity, Float.valueOf(value.toString()));
                break;
            case "float":
                field.setFloat(entity, Float.parseFloat(value.toString()));
                break;
            case "Double":
                field.set(entity, Double.valueOf(value.toString()));
                break;
            case "double":
                field.setDouble(entity, Double.parseDouble(value.toString()));
                break;
            case "Boolean":
                field.set(entity, Boolean.valueOf(value.toString()));
                break;
            case "boolean":
                field.setBoolean(entity, Boolean.parseBoolean(value.toString()));
                break;
            default:
                field.set(entity, value);
        }
    }
}
